package com.sk.weichat.ui.circle;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomSheetBehavior;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.android.flexbox.JustifyContent;
import com.makeramen.roundedimageview.RoundedImageView;
import com.mikhaellopez.circularprogressbar.CircularProgressBar;
import com.sk.im.audio.RecordManager;
import com.sk.im.audio.VoicePlayer;
import com.sk.weichat.AppConstant;
import com.sk.weichat.R;
import com.sk.weichat.adapter.MessageLocalVideoFile;
import com.sk.weichat.adapter.MessageVideoFile;
import com.sk.weichat.adapter.SelectSubjectItemAdapter;
import com.sk.weichat.adapter.SubjectItemAdapter;
import com.sk.weichat.audio.RecordStateListener;
import com.sk.weichat.audio_x.VoiceAnimView;
import com.sk.weichat.bean.Area;
import com.sk.weichat.bean.DynamicLoactionBean;
import com.sk.weichat.bean.SubjectItemBean;
import com.sk.weichat.bean.UploadFileResult;
import com.sk.weichat.bean.VideoFile;
import com.sk.weichat.bean.message.ChatMessage;
import com.sk.weichat.db.InternationalizationHelper;
import com.sk.weichat.db.dao.VideoFileDao;
import com.sk.weichat.helper.AvatarHelper;
import com.sk.weichat.helper.DialogHelper;
import com.sk.weichat.helper.LoginHelper;
import com.sk.weichat.helper.ThumbnailHelper;
import com.sk.weichat.helper.UploadService;
import com.sk.weichat.okhttp.GsonHelper;
import com.sk.weichat.ui.account.SMSLoginActivity;
import com.sk.weichat.ui.base.BaseActivity;
import com.sk.weichat.ui.circle.range.SeeCircleActivity;
import com.sk.weichat.ui.contacts.label.SelectLabelFriendActivity;
import com.sk.weichat.ui.groupchat.TabSelectContactsActivity;
import com.sk.weichat.ui.message.ChatActivity;
import com.sk.weichat.ui.tool.MultiImagePreviewActivity;
import com.sk.weichat.util.AppUtils;
import com.sk.weichat.util.BitmapUtil;
import com.sk.weichat.util.CameraUtil;
import com.sk.weichat.util.DeviceInfoUtil;
import com.sk.weichat.util.MediaFile;
import com.sk.weichat.util.PermissionUtil;
import com.sk.weichat.util.TimeUtils;
import com.sk.weichat.util.ToastUtil;
import com.sk.weichat.util.UiUtils;
import com.sk.weichat.util.UploadCacheUtils;
import com.sk.weichat.util.VideoUtil;
import com.sk.weichat.video.EasyCameraActivity;
import com.sk.weichat.video.MessageEventGpu;
import com.sk.weichat.video.VideoRecorderActivity;
import com.sk.weichat.view.MaxTextTwoLengthFilter;
import com.sk.weichat.view.MyGridView;
import com.sk.weichat.view.SelectionFrame;
import com.sk.weichat.view.SquareCenterImageView;
import com.sk.weichat.view.SubjectButtomDialog;
import com.sk.weichat.view.TipDialog;
import com.sk.weichat.volley.Result;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.callback.ListCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ArrayResult;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.io.File;
import java.io.FileOutputStream;
import java.io.RandomAccessFile;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;
import fm.jiecao.jcvideoplayer_lib.JVCideoPlayerStandardSecond;
import okhttp3.Call;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

import static android.view.View.VISIBLE;
import static com.sk.weichat.audio_x.VoicePlayer.instance;

/**
 * @Author: chenzl
 * @ClassName: PublishDynamicActivity
 * @Description: 发布动态
 * @CreateDate: 2019/10/22 9:14
 */
public class PublishDynamicActivity extends BaseActivity implements View.OnClickListener, PermissionUtil.OnRequestPermissionsResultCallbacks {

    private static final int REQUEST_MICROPHONE_CODE = 1005;
//    private static final int REQUEST_CAMERA_CODE = 1008;
    private static final int REQUEST_CAMERA_VIDEO = 1009;

    public static final int DYNAMIC_LOCATION_INTENT = 0;
    public static final int DYNAMIC_SEARCH_LOCATION_INTENT = 1;
    private static final int REQUEST_CODE_PICK_PHOTO = 2;     // 图库
//    private static final int REQUEST_CODE_PICK_VIDEO = 3;     // 视频

    private static final int REQUEST_CODE_SELECT_TYPE = 4;    // 谁可以看
    private static final int DYNAMIC_ALT_INTENT = 5;//Alt


    private RelativeLayout rt_main_dynamic;
    private ImageView iv_title_left;
    private RoundedImageView avatar_img;
    private TextView btn_title_right;

    private EditText edit_text;
    private RelativeLayout chat_warp_view;
    private VoiceAnimView chat_voice;
    private ImageView image_voice_del;
    private MyGridView mGridView;

    private ImageView image_pic;

    //定位
    private LinearLayout ll_location;
    private TextView tv_locationwhere;
    private View view_location_line;
    private ImageView image_location_close;


    //话题
    private RecyclerView recy_had_add_subject;
    private ImageView image_subject;

    private TextView tv_subject_close;
    private TextView tv_subject_add;
    private EditText etit_add_subject;
    private ImageView iv_clear_text;
    private TextView tv_cancel;

    private LinearLayout ll_create_subject;
    private TextView tv_create_subject;

    private LinearLayout ll_select_subject;
    private RecyclerView recycler_select_subject;

    private LinearLayout ll_default_subject;
    private RecyclerView recycler_default_subject;

    private CheckBox cb_ban;
    //可见状态
    private LinearLayout ll_visible_status;
    private ImageView image_visible_status;
    private TextView tv_visible_status;
    /*
     * 语音
     * */
    private ImageView image_voice;
    private RelativeLayout dynamic_voice_view;
    private Button btn_Voice;
    private Button btn_record_del;
    private Button btn_record_sure;
    private TextView tv_voice_tip;
    private CircularProgressBar mCprogressVoice;

    //视频
    private ImageView image_camera;
    private RelativeLayout rt_video;
    private JVCideoPlayerStandardSecond iv_video;
    private TextView tv_video_time;
    private ImageView image_video_del;
    /*
     * Alt
     * */
    private ImageView image_alt;
    private TextView tv_alt_numble;


    private GridViewAdapter mAdapter;
    private ArrayList<String> mPhotoList;
    private InputMethodManager mInputManager;
    private Handler mHandler = new Handler();

    // 默认为公开
    private int visible = 1;
    // 部分可见 || 不给谁看 有值 用于恢复谁可以看的界面
    private String str1;
    private String str2;
    private String str3;
    private String lookPeople;
//    private boolean fansLook = false;//是否粉丝可见


    private boolean isRecording;//录音
    private boolean isRecorded;//录音完成
    private boolean isPlaying;//播放
    private int mMaxRecordTime = 60;// 最大录制时长 default == 60
    private int mLastRecordTime;// 剩余录制时长
    private int RecordTime;//录音时长
    private RecordManager mRecordManager; // 音频录制管理类
//    private List<String> mVoicePathList = new ArrayList<>();
    private String mVoiceFinalPath; // 最终合并的文件路径
    private VoicePlayer mVoicePlayer; // 音频播放器
    private String mRecordData;


    private SubjectButtomDialog bottomSheetDialog;//添加话题弹窗
    private SelectSubjectItemAdapter mSelectSubjectItemAdapter;
    private List<String> mSubjectSelect = new ArrayList<>();

    private SubjectItemAdapter mSubjectDefaultItemAdapter;
    private List<SubjectItemBean> mSubjectDefault = new ArrayList<>();

    private List<String> mAltFriendList = new ArrayList<>();

    private DynamicLoactionBean.LoactionResult mLoactionResult = null;
    //动态标记（ 1=求职消息、2=招聘消息、3=普通消息、4=广场动态，5=城市动态）
    private int flag;

    //基础属性 1=文字消息、2=图文消息、3=语音消息、4=视频消息、 5=文件消息 、 6=SDK分享消息
    private int type = 1;
    private String mImageData;
    private String mVideoData;
    private String mVideoFilePath;
    private Bitmap mThumbBmp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_publish_dynamic);
        getSupportActionBar().hide();
        mInputManager = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        mPhotoList = new ArrayList<>();
        mAdapter = new GridViewAdapter();
        flag = getIntent().getIntExtra("flag", 0);
        // 注册EventBus
        EventBus.getDefault().register(this);
        initView();
        initSubjectView();

    }

    private void initView() {

        rt_main_dynamic = findViewById(R.id.rt_main_dynamic);
        iv_title_left = findViewById(R.id.iv_title_left);
        avatar_img = findViewById(R.id.avatar_img);
        AvatarHelper.getInstance().displayAvatar(coreManager.getSelf().getNickName(), coreManager.getSelf().getUserId(), avatar_img, false);

        btn_title_right = findViewById(R.id.btn_title_right);
        iv_title_left.setOnClickListener(this);
        btn_title_right.setOnClickListener(this);
        edit_text = findViewById(R.id.edit_text);
        edit_text.setOnClickListener(this);
        edit_text.setFilters(new InputFilter[]{new MaxTextTwoLengthFilter(2000)});
        edit_text.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() == 0) {
                    if (type == 1) {
                        btn_title_right.setTextColor(getResources().getColor(R.color.color_8C8C8C));
                        btn_title_right.setEnabled(false);
                    }
                } else {
                    btn_title_right.setTextColor(getResources().getColor(R.color.blue));
                    btn_title_right.setEnabled(true);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        chat_warp_view = findViewById(R.id.chat_warp_view);
        chat_voice = findViewById(R.id.chat_voice);
        image_voice_del = findViewById(R.id.image_voice_del);
        mGridView = findViewById(R.id.grid_view);
        mGridView.setAdapter(mAdapter);


        mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                int viewType = mAdapter.getItemViewType(position);
                if (viewType == 1) {
                    openPhoto();
                } else {
                    Intent intent = new Intent(PublishDynamicActivity.this, MultiImagePreviewActivity.class);
                    intent.putExtra(AppConstant.EXTRA_IMAGES, mPhotoList);
                    intent.putExtra(AppConstant.EXTRA_POSITION, position);
                    intent.putExtra(AppConstant.EXTRA_CHANGE_SELECTED, false);
                    startActivity(intent);
                }
            }
        });
        image_pic = findViewById(R.id.image_pic);
        image_pic.setOnClickListener(this);
        cb_ban = findViewById(R.id.cb_ban);
        //可见状态
        ll_visible_status = findViewById(R.id.ll_visible_status);
        image_visible_status = findViewById(R.id.image_visible_status);
        tv_visible_status = findViewById(R.id.tv_visible_status);
        ll_visible_status.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(PublishDynamicActivity.this, SeeCircleActivity.class);
                intent.putExtra("THIS_CIRCLE_TYPE", visible - 1);
                intent.putExtra("THIS_CIRCLE_PERSON_RECOVER1", str1);
                intent.putExtra("THIS_CIRCLE_PERSON_RECOVER2", str2);
                intent.putExtra("THIS_CIRCLE_PERSON_RECOVER3", str3);
//                intent.putExtra("fansLook",fansLook);
                startActivityForResult(intent, REQUEST_CODE_SELECT_TYPE);
            }
        });
        //话题
        recy_had_add_subject = findViewById(R.id.recy_had_add_subject);
        //设置布局管理器
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recy_had_add_subject.setLayoutManager(layoutManager);

        image_subject = findViewById(R.id.image_subject);
        image_subject.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 先加载默认话题
                loadDefaultSubject();

            }
        });
        /* 定位*/
        ll_location = findViewById(R.id.ll_location);
        tv_locationwhere = findViewById(R.id.tv_locationwhere);
        view_location_line = findViewById(R.id.view_location_line);
        image_location_close = findViewById(R.id.image_location_close);
        tv_locationwhere.setText("你在哪？");
        ll_location.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(PublishDynamicActivity.this, DynamicLocationListActivity.class), DYNAMIC_LOCATION_INTENT);
            }
        });

        image_location_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tv_locationwhere.setText("你在哪？");
                tv_locationwhere.setTextColor(getResources().getColor(R.color.color_8C8C8C));
                view_location_line.setVisibility(View.GONE);
                image_location_close.setVisibility(View.GONE);
            }
        });

        /*语音*/
        image_voice = findViewById(R.id.image_voice);
        dynamic_voice_view = findViewById(R.id.dynamic_voice_view);
        btn_Voice = findViewById(R.id.btn_Voice);
        mCprogressVoice = findViewById(R.id.cprogress_voice);
        btn_record_del = findViewById(R.id.btn_record_del);
        btn_record_sure = findViewById(R.id.btn_record_sure);
        tv_voice_tip = findViewById(R.id.tv_voice_tip);

        image_voice_del.setOnClickListener(this);
        image_voice.setOnClickListener(this);
        btn_Voice.setOnClickListener(this);
        btn_record_del.setOnClickListener(this);
        btn_record_sure.setOnClickListener(this);
        mRecordManager = RecordManager.getInstance();
        mRecordManager.setVoiceVolumeListener(recordStateListener);

        image_camera = findViewById(R.id.image_camera);
        image_camera.setOnClickListener(this);
        rt_video = findViewById(R.id.rt_video);
        iv_video = findViewById(R.id.iv_video);
        image_video_del = findViewById(R.id.image_video_del);
        tv_video_time = findViewById(R.id.tv_video_time);
        image_video_del.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mVideoFilePath = "";
                mGridView.setVisibility(VISIBLE);
                rt_video.setVisibility(View.GONE);
                type = 1;
                if (TextUtils.isEmpty(edit_text.getText().toString())) {
                    btn_title_right.setTextColor(getResources().getColor(R.color.color_8C8C8C));
                    btn_title_right.setEnabled(false);
                }
                mThumbBmp = null;
            }
        });

        image_alt = findViewById(R.id.image_alt);
        tv_alt_numble = findViewById(R.id.tv_alt_numble);
        image_alt.setOnClickListener(this);
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (isVoiceShow()) {
//            closeKeyboard();
            changeChatVoiceView(false);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mRecordManager.isRunning()){
            deleteVoice();
        }
    }

    /**
     * @author: czl
     * @description 初始化 添加话题布局
     * @date: 2019/10/24 17:33
     */
    private void initSubjectView() {
        View contentView = View.inflate(PublishDynamicActivity.this, R.layout.layout_subject_buttom_dialog, null);
        tv_subject_close = contentView.findViewById(R.id.tv_subject_close);
        tv_subject_add = contentView.findViewById(R.id.tv_subject_add);
        etit_add_subject = contentView.findViewById(R.id.etit_add_subject);
        etit_add_subject.setFilters(new InputFilter[]{new MaxTextTwoLengthFilter(24)});
        iv_clear_text = contentView.findViewById(R.id.iv_clear_text);
        tv_cancel = contentView.findViewById(R.id.tv_cancel);
        //创建话题
        ll_create_subject = contentView.findViewById(R.id.ll_create_subject);
        tv_create_subject = contentView.findViewById(R.id.tv_create_subject);

        //已选话题
        ll_select_subject = contentView.findViewById(R.id.ll_select_subject);
        recycler_select_subject = contentView.findViewById(R.id.recycler_select_subject);

        //默认话题
        ll_default_subject = contentView.findViewById(R.id.ll_default_subject);
        recycler_default_subject = contentView.findViewById(R.id.recycler_default_subject);
        //设置布局管理器
        FlexboxLayoutManager flexboxLayoutManager1 = new FlexboxLayoutManager(PublishDynamicActivity.this);
        //flexDirection 属性决定主轴的方向（即项目的排列方向）。类似 LinearLayout 的 vertical 和 horizontal。
        flexboxLayoutManager1.setFlexDirection(FlexDirection.ROW);//主轴为水平方向，起点在左端。
        //flexWrap 默认情况下 Flex 跟 LinearLayout 一样，都是不带换行排列的，但是flexWrap属性可以支持换行排列。
        flexboxLayoutManager1.setFlexWrap(FlexWrap.WRAP);//按正常方向换行
        //justifyContent 属性定义了项目在主轴上的对齐方式。
        flexboxLayoutManager1.setJustifyContent(JustifyContent.FLEX_START);//交叉轴的起点对齐。
        recycler_select_subject.setLayoutManager(flexboxLayoutManager1);
        mSelectSubjectItemAdapter = new SelectSubjectItemAdapter(mSubjectSelect);
        recycler_select_subject.setAdapter(mSelectSubjectItemAdapter);
        recy_had_add_subject.setAdapter(mSelectSubjectItemAdapter);

        mSelectSubjectItemAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                for (int i = 0; i < mSubjectDefault.size(); i++) {
                    if (mSubjectDefault.get(i).getTopicName().equals(mSubjectSelect.get(position))) {
                        mSubjectDefault.get(i).setSelect(false);
                        mSubjectDefaultItemAdapter.notifyDataSetChanged();
                        break;
                    }
                }
                mSubjectSelect.remove(position);
                mSelectSubjectItemAdapter.notifyDataSetChanged();
                if (mSubjectSelect.size() > 0) {
                    tv_subject_add.setTextColor(getResources().getColor(R.color.blue));
                    tv_subject_add.setEnabled(true);
                    ll_select_subject.setVisibility(VISIBLE);
                } else {
                    tv_subject_add.setTextColor(getResources().getColor(R.color.color_BDC2C8));
                    tv_subject_add.setEnabled(false);
                    ll_select_subject.setVisibility(View.GONE);
                }
            }
        });
        //设置布局管理器
        FlexboxLayoutManager flexboxLayoutManager = new FlexboxLayoutManager(PublishDynamicActivity.this);
        //flexDirection 属性决定主轴的方向（即项目的排列方向）。类似 LinearLayout 的 vertical 和 horizontal。
        flexboxLayoutManager.setFlexDirection(FlexDirection.ROW);//主轴为水平方向，起点在左端。
        //flexWrap 默认情况下 Flex 跟 LinearLayout 一样，都是不带换行排列的，但是flexWrap属性可以支持换行排列。
        flexboxLayoutManager.setFlexWrap(FlexWrap.WRAP);//按正常方向换行
        //justifyContent 属性定义了项目在主轴上的对齐方式。
        flexboxLayoutManager.setJustifyContent(JustifyContent.FLEX_START);//交叉轴的起点对齐。
        recycler_default_subject.setLayoutManager(flexboxLayoutManager);
        mSubjectDefaultItemAdapter = new SubjectItemAdapter(mSubjectDefault);
        mSubjectDefaultItemAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {

                if (mSubjectSelect.size() >= 5) {
                    if (mSubjectDefault.get(position).isSelect()){
                        return;
                    }
                    ToastUtil.showToast(PublishDynamicActivity.this, "最多只能添加5个话题");
                } else {
                    if (mSubjectSelect.size()>0){
                        for (int i = 0; i <mSubjectSelect.size() ; i++) {
                            if (mSubjectSelect.get(i).equals(mSubjectDefault.get(position).getTopicName())){
                                ToastUtil.showToast(mContext,"该话题已存在，请更换");
                                return;
                            }
                        }
                    }
                    if (mSubjectDefault.get(position).isSelect()) {
                        return;
                    } else {
                        mSubjectDefault.get(position).setSelect(true);
                        mSubjectSelect.add(mSubjectDefault.get(position).getTopicName());
                    }
                    mSubjectDefaultItemAdapter.notifyDataSetChanged();
                    if (mSubjectSelect.size() > 0) {
                        tv_subject_add.setTextColor(getResources().getColor(R.color.blue));
                        tv_subject_add.setEnabled(true);
                        ll_select_subject.setVisibility(VISIBLE);
                    } else {
                        tv_subject_add.setTextColor(getResources().getColor(R.color.color_BDC2C8));
                        tv_subject_add.setEnabled(false);
                        ll_select_subject.setVisibility(View.GONE);
                    }
                    mSelectSubjectItemAdapter.notifyDataSetChanged();
                }
            }
        });
        recycler_default_subject.setAdapter(mSubjectDefaultItemAdapter);
        bottomSheetDialog = new SubjectButtomDialog(PublishDynamicActivity.this);
        bottomSheetDialog.setContentView(contentView);
        bottomSheetDialog.getWindow().findViewById(R.id.design_bottom_sheet).setBackgroundResource(android.R.color.transparent);
        BottomSheetBehavior mDialogBehavior = BottomSheetBehavior.from((View) contentView.getParent());
        mDialogBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(@NonNull View bottomSheet, int newState) {
                if (newState == BottomSheetBehavior.STATE_HIDDEN) {
                    bottomSheetDialog.dismiss();
                    mDialogBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
                }
            }

            @Override
            public void onSlide(@NonNull View bottomSheet, float slideOffset) {
            }
        });

        tv_subject_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AppUtils.hideSoftKeyboard(PublishDynamicActivity.this, etit_add_subject);
                bottomSheetDialog.dismiss();
            }
        });
        if (mSubjectSelect.size() == 0) {
            tv_subject_add.setTextColor(getResources().getColor(R.color.color_BDC2C8));
        } else {
            tv_subject_add.setTextColor(getResources().getColor(R.color.blue));
        }
        tv_subject_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AppUtils.hideSoftKeyboard(PublishDynamicActivity.this, etit_add_subject);
                bottomSheetDialog.dismiss();
            }
        });
        /* 输入框是否获取焦点*/
        etit_add_subject.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    tv_cancel.setVisibility(VISIBLE);
                } else {
                    tv_cancel.setVisibility(View.GONE);
                }
            }
        });

        /* 输入框输入监听*/
        etit_add_subject.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s == null || s.length() == 0) {
                    iv_clear_text.setVisibility(View.INVISIBLE);
                    ll_create_subject.setVisibility(View.GONE);
                    if (mSubjectSelect.size() > 0) {
                        ll_select_subject.setVisibility(View.VISIBLE);
                    } else {
                        ll_select_subject.setVisibility(View.GONE);
                    }
                    ll_default_subject.setVisibility(View.VISIBLE);
                    return;
                }
                String replaceBlank = AppUtils.replaceBlank(s.toString());
//                etit_add_subject.setText(replaceBlank);
                iv_clear_text.setVisibility(View.VISIBLE);
                ll_create_subject.setVisibility(VISIBLE);
                tv_create_subject.setText(mContext.getString(R.string.subject, replaceBlank));
                ll_select_subject.setVisibility(View.GONE);
                ll_default_subject.setVisibility(View.GONE);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        iv_clear_text.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etit_add_subject.setText("");
            }
        });

        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etit_add_subject.setText("");
                etit_add_subject.setFocusable(false);
                etit_add_subject.setFocusableInTouchMode(false);
                AppUtils.hideSoftKeyboard(PublishDynamicActivity.this, etit_add_subject);
            }
        });
        tv_create_subject.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mSubjectSelect.size() >= 5) {
                    ToastUtil.showToast(PublishDynamicActivity.this, "最多只能添加5个话题");
                    return;
                }
                addSubject(etit_add_subject.getText().toString());
            }
        });
        etit_add_subject.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etit_add_subject.setFocusable(true);
                etit_add_subject.setFocusableInTouchMode(true);
                etit_add_subject.requestFocus();
                AppUtils.showSoftKeyboard(PublishDynamicActivity.this, etit_add_subject);
            }
        });
    }


    @Override
    public void onClick(View v) {
        if (v == iv_title_left) {
            finishActivity();

        } else if (v == btn_title_right) {
            if (type == 2 || type == 3 || type == 4) {
                new UploadTask().execute();
            } else {
                sendDynamic();
            }

        } else if (v == edit_text) {
            changeChatVoiceView(false);
        } else if (v == image_pic) {
            if (type != 1 && type != 2) {
                if (type==4){
                    ToastUtil.showToast(this, "视频只能上传1个");
                }else {
                    ToastUtil.showToast(this, "不支持照片和其他媒体一起上传");
                }
                return;
            }
            if (mPhotoList.size() == 9) {
                ToastUtil.showToast(this, "最多只能上传9张图片，请先删除");
                return;
            }
            openPhoto();
        } else if (v == image_voice) {
            if (type != 1 && type != 3) {
                ToastUtil.showToast(this, "不支持语音和其他媒体一起上传");
                return;
            }
            if (isVoiceShow()) {
                changeChatVoiceView(false);
            } else {// 录音布局没有显示,那么点击则是显示录音，隐藏表情、更多、键盘布局
                Activity activity = (Activity) mContext;
                boolean isReadContacts = PermissionUtil.checkSelfPermissions(activity, new String[]{Manifest.permission.RECORD_AUDIO});
                if (isReadContacts) {
                    showVoiceBtn();
                } else {
                    PermissionUtil.requestPermissions(activity, 0x01, new String[]{Manifest.permission.RECORD_AUDIO});
                }
            }
        } else if (v == image_camera) {
            if (type != 1 && type == 3) {
                ToastUtil.showToast(this, "不支持视频和其他媒体一起上传");
                return;
            }else
                if (type==4){
                ToastUtil.showToast(this, "视频只能上传1个");
                return;
            }
            boolean isReadContacts = PermissionUtil.checkSelfPermissions(PublishDynamicActivity.this, new String[]{Manifest.permission.CAMERA});
            if (isReadContacts) {
                openVideo();
            } else {
                PermissionUtil.requestPermissions(PublishDynamicActivity.this, 0x02, new String[]{Manifest.permission.CAMERA});
            }

        } else if (v == btn_Voice) {
            // 防止连续点击，
            if (!UiUtils.isNormalClick(v)) {
                return;
            }
            if (isRecording) {
                if (isRecorded) {
                    if (isPlaying) {
                        mVoicePlayer.stop();
                        ChangePlayVoice(false);
                    } else {
                        //判断语音id 是否为空  为空则未确定添加语 防止正在播放
                        if (!TextUtils.isEmpty(instance().getVoiceMsgId())){
                            chat_voice.stop();
                        }
                        playVoice();
                        mCprogressVoice.setProgressMax(RecordTime);
                        ChangePlayVoice(true);
                    }
                } else {
                    isRecorded = true;
                    mRecordManager.stop();
                    mCprogressVoice.setProgress(0);
                    mCprogressVoice.setVisibility(View.GONE);
                    //显示删除和确定按钮
                    btn_record_del.setVisibility(VISIBLE);
                    btn_record_sure.setVisibility(VISIBLE);
                }
            } else {
                mRecordManager.startRecord();
            }
        } else if (v == btn_record_del || v == image_voice_del) {//删除语音
            deleteVoice();
        } else if (v == btn_record_sure) {//确认语音

            changeChatVoiceView(false);
            if (isPlaying) {
                mVoicePlayer.stop();
                ChangePlayVoice(false);
            }

//            linkVoice();

            mGridView.setVisibility(View.GONE);
            chat_warp_view.setVisibility(VISIBLE);
            type = 3;
            btn_title_right.setTextColor(getResources().getColor(R.color.blue));
            btn_title_right.setEnabled(true);

            if (!TextUtils.isEmpty(instance().getVoiceMsgId())){
                chat_voice.stop();
                instance().removeVoicePlay();
            }
            ChatMessage chatMessage = new ChatMessage();
            chatMessage.setMySend(true);
            chatMessage.setPacketId("100");
            chatMessage.setFilePath(mVoiceFinalPath);
            chatMessage.setTimeLen(RecordTime);
            chat_voice.fillData(chatMessage);
            chat_voice.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (isPlaying){
                        if (isPlaying) {
                            mVoicePlayer.stop();
                        }
                    }
                    instance().playVoice(chat_voice);
                }
            });

        } else if (v == image_alt) {
            Intent intent = new Intent(this, TabSelectContactsActivity.class);
            intent.putExtra("alt_userid", (Serializable) mAltFriendList);
            intent.putExtra("AltFriends", true);
            startActivityForResult(intent, DYNAMIC_ALT_INTENT);
        }
    }


    /**
     * @author: czl
     * @description 退出
     * @date: 2019/10/30 14:07
     */
    private void finishActivity(){
        if (btn_title_right.isEnabled()){
            SelectionFrame selectionFrame = new SelectionFrame(this);
            selectionFrame.setSomething(null, "你要放弃发布吗？","放弃","继续编辑", new SelectionFrame.OnSelectionFrameClickListener() {
                @Override
                public void cancelClick() {
                    finish();
                }
                @Override
                public void confirmClick() {
                    selectionFrame.hide();
                }
            });
            selectionFrame.show();
        }else {
            finish();
        }
    }

    /**
     * @author: czl
     * @description 删除语音
     * @date: 2019/10/30 17:58
     */
    private void deleteVoice(){
        if (chat_warp_view.getVisibility() == VISIBLE) {
            chat_warp_view.setVisibility(View.GONE);
            //判断语音id 是否为空  为空则未确定添加语 防止语音正在播放
            if (!TextUtils.isEmpty(instance().getVoiceMsgId())){
                chat_voice.stop();
            }
            mGridView.setVisibility(View.VISIBLE);
            type = 1;
            if (TextUtils.isEmpty(edit_text.getText().toString())) {
                btn_title_right.setTextColor(getResources().getColor(R.color.color_8C8C8C));
                btn_title_right.setEnabled(false);
            }
        }
        if (isPlaying) {
            mVoicePlayer.stop();
            ChangePlayVoice(false);
        }
        isRecording = false;
        isRecorded = false;
        isPlaying = false;
        mRecordManager.cancel();
//            linkVoice();
        if (!TextUtils.isEmpty(mVoiceFinalPath)){
            File file = new File(mVoiceFinalPath);
            if (file.exists()) {
                file.delete();
                mVoiceFinalPath = "";
//                mVoicePathList.clear();
            }
        }
        btn_record_del.setVisibility(View.GONE);
        btn_record_sure.setVisibility(View.GONE);
        btn_Voice.setBackgroundResource(R.drawable.btn_chat_voice_normal);
        tv_voice_tip.setTextColor(getResources().getColor(R.color.color_929292));
        tv_voice_tip.setText("点击录音");
        mCprogressVoice.setProgressMax(60);
        mCprogressVoice.setProgress(0);
        mCprogressVoice.setVisibility(View.GONE);
        mMaxRecordTime = 60;
    }

    /**
     * @author: czl
     * @description 发布动态
     * @date: 2019/10/28 14:47
     */
    private void sendDynamic() {
        Map<String, String> params = new HashMap<String, String>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        // 基础属性 1=文字消息、2=图文消息、3=语音消息、4=视频消息、 5=文件消息 、 6=SDK分享消息
        params.put("type", String.valueOf(type));
        // 动态标记（ 1=求职消息、2=招聘消息、3=普通消息、4=广场动态，5=城市动态）
        params.put("flag", String.valueOf(flag));

        // 消息隐私范围：1=公开；2=私密；3=部分选中好友可见；4=不给谁看
        params.put("visible", String.valueOf(visible));
        if (visible == 3) {
            // 谁可以看
            params.put("userLook", lookPeople);
        } else if (visible == 4) {
            // 不给谁看
            params.put("userNotLook", lookPeople);
        }
        // 提醒谁看
        if (mAltFriendList.size() > 0) {
            params.put("userRemindLook", GsonHelper.GsonString(mAltFriendList));
        }

        // 消息内容
        params.put("text", edit_text.getText().toString());
        //话题名称的集合的json字符串
        params.put("topicNames", GsonHelper.GsonString(mSubjectSelect));

        params.put("videos", mVideoData);
        if (!TextUtils.isEmpty(mImageData) && !mImageData.equals("{}") && !mImageData.equals("[{}]")) {
            params.put("images", mImageData);
        }

        /**
         * 所在位置
         */
        if (mLoactionResult != null) {
            // 纬度
            params.put("latitude", String.valueOf(mLoactionResult.getLocation().getLat()));
            // 经度
            params.put("longitude", String.valueOf(mLoactionResult.getLocation().getLng()));
            // 位置
            params.put("location", mLoactionResult.getName());
        }

        params.put("isAllowComment", cb_ban.isChecked() ? String.valueOf(1) : String.valueOf(0));

        // 必传，之前删除该字段，发布说说，服务器返回接口内部异常
        Area area = Area.getDefaultCity();
        if (area != null) {
            params.put("cityId", String.valueOf(area.getId()));// 城市Id
        } else {
            params.put("cityId", "0");
        }
        params.put("audios", mRecordData);

        /**
         * 附加信息
         */
        // 手机型号
        params.put("model", DeviceInfoUtil.getModel());
        // 手机操作系统版本号
        params.put("osVersion", DeviceInfoUtil.getOsVersion());
        if (!TextUtils.isEmpty(DeviceInfoUtil.getDeviceId(mContext))) {
            // 设备序列号
            params.put("serialNumber", DeviceInfoUtil.getDeviceId(mContext));
        }

        DialogHelper.showDefaulteMessageProgressDialog(PublishDynamicActivity.this);

        HttpUtils.get().url(coreManager.getConfig().MSG_ADD_URL)
                .params(params)
                .build()
                .execute(new BaseCallback<String>(String.class) {

                    @Override
                    public void onResponse(ObjectResult<String> result) {
                        DialogHelper.dismissProgressDialog();
                        ToastUtil.showToast(mContext,"发送成功");
                        Intent intent = new Intent();
                        intent.putExtra(AppConstant.EXTRA_MSG_ID, result.getData());
                        setResult(RESULT_OK, intent);
                        finish();
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        DialogHelper.dismissProgressDialog();
                        ToastUtil.showErrorNet(PublishDynamicActivity.this);
                    }
                });

    }

    /**
     * @author: czl
     * @description 加载系统默认 话题
     * @date: 2019/10/24 18:22
     */
    private void loadDefaultSubject() {
        DialogHelper.showDefaulteMessageProgressDialog(this);
        HashMap<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        HttpUtils.post().url(coreManager.getConfig().QUERY_SYS_TOPIC)
                .params(params)
                .build()
                .execute(new ListCallback<SubjectItemBean>(SubjectItemBean.class) {
                    @Override
                    public void onResponse(ArrayResult<SubjectItemBean> result) {
                        DialogHelper.dismissProgressDialog();
                        if (result.getResultCode() == 1) {
                            List<SubjectItemBean> datas = result.getData();
                            if (mSubjectDefault.size() > 0) {
                                mSubjectDefault.clear();
                            }
                            if (mSubjectSelect.size() > 0) {
                                for (int i = 0; i < mSubjectSelect.size(); i++) {
                                    for (int j = 0; j < datas.size(); j++) {
                                        if (datas.get(j).getTopicName().equals(mSubjectSelect.get(i))) {
                                            datas.get(j).setSelect(true);
                                            break;
                                        }
                                    }
                                }
                            }
                            mSubjectDefault.addAll(datas);
                            mSubjectDefaultItemAdapter.notifyDataSetChanged();
                            bottomSheetDialog.show();
                            new Handler().postDelayed(new Runnable(){
                                public void run() {
                                    //要执行的任务
                                    //弹出键盘
                                    etit_add_subject.setFocusable(true);
                                    etit_add_subject.setFocusableInTouchMode(true);
                                    etit_add_subject.requestFocus();
                                    AppUtils.showSoftKeyboard(PublishDynamicActivity.this, etit_add_subject);
                                }
                            }, 200);

                        } else {
                            ToastUtil.showToast(PublishDynamicActivity.this, result.getResultMsg());
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        DialogHelper.dismissProgressDialog();
                        ToastUtil.showToast(PublishDynamicActivity.this, e.getMessage());
                    }
                });
    }

    /**
     * @author: czl
     * @description 添加话题
     * @date: 2019/10/25 10:47
     */
    private void addSubject(String topicName) {
        DialogHelper.showDefaulteMessageProgressDialog(this);
        HashMap<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("topicName", topicName);
        HttpUtils.post().url(coreManager.getConfig().ADD_TOPIC).params(params).build().execute(new BaseCallback<SubjectItemBean>(SubjectItemBean.class) {
            @Override
            public void onResponse(ObjectResult<SubjectItemBean> result) {
                DialogHelper.dismissProgressDialog();
                if (result.getResultCode() == 1) {
                    mSubjectSelect.add(result.getData().getTopicName());
                    mSelectSubjectItemAdapter.notifyDataSetChanged();
                    etit_add_subject.setText("");
                } else if (result.getResultCode() == 0) {
                    for (int i = 0; i < mSubjectSelect.size(); i++) {
                        if (mSubjectSelect.get(i).equals(topicName)) {
                            ToastUtil.showToast(PublishDynamicActivity.this, result.getResultMsg());
                            return;
                        }
                    }
                    mSubjectSelect.add(topicName);
                    mSelectSubjectItemAdapter.notifyDataSetChanged();
                    etit_add_subject.setText("");
                    tv_subject_add.setTextColor(getResources().getColor(R.color.blue));
                    tv_subject_add.setEnabled(true);

                } else {
                    ToastUtil.showToast(PublishDynamicActivity.this, result.getResultMsg());
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                DialogHelper.dismissProgressDialog();
                ToastUtil.showToast(PublishDynamicActivity.this, e.getMessage());
            }
        });
    }

    /**
     * @author: czl
     * @description 显示语音按钮
     * @date: 2019/10/22 16:40
     */
    public void showVoiceBtn() {
        closeKeyboard();
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                changeChatVoiceView(true);
            }
        }, 200);
    }

    private void closeKeyboard() {
        mInputManager.hideSoftInputFromWindow(edit_text.getApplicationWindowToken(), 0);
    }

    private boolean isVoiceShow() {
        return dynamic_voice_view != null && dynamic_voice_view.getVisibility() != View.GONE;
    }

    /**
     * 显示或语音布局
     */
    private void changeChatVoiceView(boolean show) {
        boolean isShowing = isVoiceShow();
        if (!show && isShowing == show) {
            return;
        }
        if (show) {
            dynamic_voice_view.setVisibility(VISIBLE);
            Drawable drawable = image_voice.getDrawable();
            image_voice.setTag(drawable);
            image_voice.setImageResource(R.drawable.icon_voice_active);
            Map<Integer, Integer> viewMap = new HashMap<>();
            viewMap.put(R.id.image_voice, R.drawable.icon_voice_active);
            //记录选中的图标id
            image_voice.setTag(viewMap);
        } else {
            dynamic_voice_view.setVisibility(View.GONE);
            Object obj = image_voice.getTag();
            if (obj != null && obj instanceof Drawable) {
                Drawable drawable = (Drawable) obj;
                image_voice.setImageDrawable(drawable);
            } else {
                image_voice.setImageResource(R.drawable.icon_voice);
            }
        }
    }

    private RecordStateListener recordStateListener = new RecordStateListener() {
        @Override
        public void onRecordStarting() {
            Log.e("zq", "onRecordStarting");
        }

        @Override
        public void onRecordStart() {
            Log.e("zq", "onRecordStart");
            changeRecorded(true);
        }


        @Override
        public void onRecordFinish(String filePath) {
            Log.e("zq", "onRecordFinish");
            changeRecorded(false);
            File file = new File(filePath);
            if (file.exists()) {
                mVoiceFinalPath = filePath;
            }
        }

        @Override
        public void onRecordCancel() {
            Log.e("zq", "onRecordCancel");
//            changeRecorded(false);
        }

        @Override
        public void onRecordVolumeChange(int v) {
            Log.e("zq", "onRecordVolumeChange");
        }

        @Override
        public void onRecordTimeChange(int seconds) {
            Log.e("zq", "onRecordTimeChange：" + seconds);

            mLastRecordTime = mMaxRecordTime - seconds;
            tv_voice_tip.setText(seconds + "″");
            tv_voice_tip.setTextColor(getResources().getColor(R.color.blue));
            RecordTime = seconds;
            if (mLastRecordTime <=0) {
                isRecorded = true;
                mRecordManager.stop();
                mCprogressVoice.setProgress(0);
                mCprogressVoice.setVisibility(View.GONE);
                //显示删除和确定按钮
                btn_record_del.setVisibility(VISIBLE);
                btn_record_sure.setVisibility(VISIBLE);
            } else {
                mCprogressVoice.setVisibility(VISIBLE);
                mCprogressVoice.setProgress(seconds);
            }
        }

        @Override
        public void onRecordTooShoot() {
            Log.e("zq", "onRecordTooShoot");
            changeRecorded(false);
            Toast.makeText(PublishDynamicActivity.this, getString(R.string.tip_record_time_too_short), Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onRecordError() {
            Log.e("zq", "onRecordError");
            changeRecorded(false);
            Toast.makeText(PublishDynamicActivity.this, getString(R.string.tip_voice_record_error), Toast.LENGTH_SHORT).show();
        }
    };

    /*
     * 更改录音状态
     * */
    private void changeRecorded(boolean flag) {
        isRecording = true;
        if (flag) {
            btn_Voice.setBackgroundResource(R.mipmap.icon_btn_record_stop);
            mCprogressVoice.setProgress(0);
            mCprogressVoice.setVisibility(View.GONE);
        } else {
            btn_Voice.setBackgroundResource(R.mipmap.icon_btn_record_play);
            mMaxRecordTime = mLastRecordTime;
        }
    }

    /**
     * @author: czl
     * @description 更改播放状态
     * @date: 2019/10/22 17:21
     */
    private void ChangePlayVoice(boolean flag) {
        isPlaying = flag;
        if (flag) {
            btn_Voice.setBackgroundResource(R.mipmap.icon_btn_record_stop);
        } else {
            btn_Voice.setBackgroundResource(R.mipmap.icon_btn_record_play);
        }
    }


    /**
     * @author: czl
     * @description 播放语音
     * @date: 2019/10/22 17:28
     */
    private void playVoice() {
        isPlaying = false;
//        linkVoice();
        mVoicePlayer = null;
        mVoicePlayer = new VoicePlayer();
        mVoicePlayer.play(mVoiceFinalPath);
        mVoicePlayer.setOnFinishPlayListener(new VoicePlayer.OnFinishPlayListener() {
            @Override
            public void onFinishPlay() {
                ChangePlayVoice(false);
                mCprogressVoice.setProgress(0);
                mCprogressVoice.setVisibility(View.GONE);
                tv_voice_tip.setText(RecordTime + "″");
            }

            @Override
            public void onSecondsChange(int seconds) {
                Log.e("onSecondsChange", seconds + "");
                int second = seconds / 1000;
                mCprogressVoice.setVisibility(VISIBLE);
                mCprogressVoice.setProgress(second);
                tv_voice_tip.setText((RecordTime - second) + "″");
                tv_voice_tip.setTextColor(getResources().getColor(R.color.blue));
            }
        });
    }

    /**
     * @author: czl
     * @description 返回键监听
     * @date: 2019/10/30 14:12
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            finishActivity();
            return false;
        }else {
            return super.onKeyDown(keyCode, event);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == DYNAMIC_LOCATION_INTENT) {
                mLoactionResult = data.getParcelableExtra("LoactionResult");
                tv_locationwhere.setText(mLoactionResult.getName());
                tv_locationwhere.setTextColor(getResources().getColor(R.color.color_00477C));
                view_location_line.setVisibility(VISIBLE);
                image_location_close.setVisibility(VISIBLE);
            } else if (requestCode == REQUEST_CODE_SELECT_TYPE) {
                // 谁可以看返回
                visible = data.getIntExtra("THIS_CIRCLE_TYPE", 1);
                tv_visible_status.setTextColor(getResources().getColor(R.color.color_00477C));
                if (visible == 1) {
                    tv_visible_status.setText(R.string.publics);
                    image_visible_status.setBackgroundResource(R.mipmap.icon_open);
                } else if (visible == 2) {
                    tv_visible_status.setText(R.string.privates);
                    image_visible_status.setBackgroundResource(R.mipmap.icon_private);
                } else if (visible == 3) {
                    lookPeople = data.getStringExtra("THIS_CIRCLE_PERSON");
                    String looKenName = data.getStringExtra("THIS_CIRCLE_PERSON_NAME");
                    tv_visible_status.setText("部分可见");
                    image_visible_status.setBackgroundResource(R.mipmap.icon_part);

                } else if (visible == 4) {
                    lookPeople = data.getStringExtra("THIS_CIRCLE_PERSON");
                    String lookName = data.getStringExtra("THIS_CIRCLE_PERSON_NAME");
                    tv_visible_status.setText("部分不可见");
                    image_visible_status.setBackgroundResource(R.mipmap.icon_partno);
                }else if (visible==6){
                    tv_visible_status.setText(R.string.fens);
                    image_visible_status.setBackgroundResource(R.mipmap.icon_fans);
                }
                str1 = data.getStringExtra("THIS_CIRCLE_PERSON_RECOVER1");
                str2 = data.getStringExtra("THIS_CIRCLE_PERSON_RECOVER2");
                str3 = data.getStringExtra("THIS_CIRCLE_PERSON_RECOVER3");
//                fansLook = data.getBooleanExtra("fansLook",false);
            } else if (requestCode == DYNAMIC_ALT_INTENT) {
                List<String> frindids = (List<String>) data.getSerializableExtra("AltFriendIdList");
                if (mAltFriendList.size() > 0) {
                    mAltFriendList.clear();
                }
                mAltFriendList.addAll(frindids);
                if (mAltFriendList.size() > 0) {
                    image_alt.setBackgroundResource(R.mipmap.alt_active);
                    tv_alt_numble.setVisibility(VISIBLE);
                    tv_alt_numble.setText(String.valueOf(mAltFriendList.size()));
                }else {
                    image_alt.setBackgroundResource(R.mipmap.alt);
                    tv_alt_numble.setVisibility(View.GONE);
                }
            } else if (requestCode == REQUEST_CODE_PICK_PHOTO) {
                if (data != null) {
                    List<String> result = Matisse.obtainPathResult(data);
                    //判断返回的文件  是图片类型 还是视频类型
                    if (MediaFile.isImageFileType(result.get(0))){
                        album(result, true);
                    }else {
                        // 只能上传一个视频  显示第一个视频
                        if (result.size()>1){
                            ToastUtil.showToast(mContext,"视频只能上传1个");
                        }
                        ShowVideoView(result.get(0));
                    }
                } else {
                    ToastUtil.showToast(this, R.string.c_photo_album_failed);
                }
            }
       /*     else if (requestCode == REQUEST_CODE_PICK_VIDEO) {
                List<String> result = Matisse.obtainPathResult(data);
                mVideoFilePath = result.get(0);
                if (TextUtils.isEmpty(mVideoFilePath)) {
                    ToastUtil.showToast(this, R.string.select_failed);
                    return;
                }
                File file = new File(mVideoFilePath);
                if (!file.exists()) {
                    ToastUtil.showToast(this, R.string.select_failed);
                    return;
                }
                ThumbnailHelper.displayVideoThumb(mContext, mVideoFilePath, iv_video.thumbImageView);
                mThumbBmp = ThumbnailHelper.makeThumb(mVideoFilePath);
                iv_video.setUp(mVideoFilePath, JVCideoPlayerStandardSecond.SCREEN_LAYOUT_NORMAL, "");
                type = 4;
                btn_title_right.setTextColor(getResources().getColor(R.color.blue));
                btn_title_right.setEnabled(true);
                mGridView.setVisibility(View.GONE);
                rt_video.setVisibility(VISIBLE);
                if (isVoiceShow()) {
                    changeChatVoiceView(false);
                }
            } */
            else if (requestCode == REQUEST_MICROPHONE_CODE) {
                boolean isReadContacts = PermissionUtil.checkSelfPermissions(PublishDynamicActivity.this, new String[]{Manifest.permission.RECORD_AUDIO});
                if (isReadContacts) {
                    showVoiceBtn();
                }
            } else if (requestCode == REQUEST_CAMERA_VIDEO) {
                boolean isReadContacts = PermissionUtil.checkSelfPermissions(PublishDynamicActivity.this, new String[]{Manifest.permission.CAMERA});
                if (isReadContacts) {
                    openVideo();
                }
            }
        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms, boolean isAllGranted) {
        if (isAllGranted) {// 请求权限返回 已全部授权
            if (requestCode == 0x01) {//录音权限
                showVoiceBtn();
            }else if (requestCode==0x02){//拍照权限
                openVideo();
            }
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms, boolean isAllDenied) {
        boolean onceAgain = PermissionUtil.deniedRequestPermissionsAgain(this, perms.toArray(new String[perms.size()]));
        String tips = "";
        if (perms.get(0).endsWith("android.permission.RECORD_AUDIO")) {
            tips = getString(R.string.permission_microphone);
        } else if (perms.get(0).endsWith("android.permission.CAMERA")) {
            tips = getString(R.string.permission_photo);
        }
        if (onceAgain) {
            TipDialog mTipDialog = new TipDialog(this);
            mTipDialog.setmConfirmOnClickListener(getString(R.string.tip_reject_permission_place_holder, tips), new TipDialog.ConfirmOnClickListener() {
                @Override
                public void confirm() {
                    if (requestCode == 0x01) {//录音权限
                        PermissionUtil.startApplicationDetailsSettings(PublishDynamicActivity.this, REQUEST_MICROPHONE_CODE);
                    } else if (requestCode == 0x02){//拍照权限
                        PermissionUtil.startApplicationDetailsSettings(PublishDynamicActivity.this, REQUEST_CAMERA_VIDEO);
                    }
                }
            });
            mTipDialog.show();
        } else {
            ToastUtil.showToast(PublishDynamicActivity.this, getString(R.string.tip_permission_reboot_place_holder, tips));
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (isRecording) {
            mRecordManager.cancel();
        }
        if (isPlaying) {
            mVoicePlayer.stop();
        }
        if (!TextUtils.isEmpty(instance().getVoiceMsgId())){
            chat_voice.stop();
        }
        mThumbBmp = null;
        EventBus.getDefault().unregister(this);

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionUtil.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    /**
     * @author: czl
     * @description 打开图片列表
     * @date: 2019/10/29 10:25
     */
    private void openPhoto() {
        Matisse.from(PublishDynamicActivity.this)
                .choose(MimeType.ofAll())//图片类型
                .countable(true)//true:选中后显示数字;false:选中后显示对号
                .maxSelectable(9 - mPhotoList.size())//可选的最大数
                .capture(false)//选择照片时，是否显示拍照
                .showSingleMediaType(true)
                .theme(R.style.Matisse_Dracula)
                .originalEnable(true)
                .maxOriginalSize(1024)//最大
                .captureStrategy(new CaptureStrategy(true, "com.hlg.yueliao.provider"))//参数1 true表示拍照存储在共有目录，false表示存储在私有目录；参数2与 AndroidManifest中authorities值相同，用于适配7.0系统 必须设置
                .imageEngine(new GlideEngine())//图片加载引擎
                .forResult(REQUEST_CODE_PICK_PHOTO);
    }

    private void openVideo() {
        boolean isReadContacts = PermissionUtil.checkSelfPermissions(PublishDynamicActivity.this, new String[]{Manifest.permission.CAMERA});
        if (isReadContacts) {

            Intent intent = new Intent();
            if (type==2){
                if (mPhotoList.size()>=9){
                    ToastUtil.showToast(mContext,"最多只能上传9张图片，请先删除");
                    return;
                }
                intent.setClass(this, EasyCameraActivity.class);
            }else {
                intent.setClass(this, VideoRecorderActivity.class);
                intent.putExtra("Dynamic",true);
            }
            startActivity(intent);
        } else {
            PermissionUtil.requestPermissions(PublishDynamicActivity.this, 0x02, new String[]{Manifest.permission.CAMERA});
        }
    }
    @Subscribe(threadMode = ThreadMode.MainThread)
    public void helloEventBus(final MessageEventGpu message) {// 拍照返回
        mPhotoList.add(message.event);
        mAdapter.notifyDataSetInvalidated();
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void helloEventBus(final MessageLocalVideoFile message) {
        ShowVideoView(message.file.getPath());
    }
    @Subscribe(threadMode = ThreadMode.MainThread)
    public void helloEventBus(final MessageVideoFile message) {
        VideoFile videoFile = new VideoFile();
        videoFile.setCreateTime(TimeUtils.f_long_2_str(System.currentTimeMillis()));
        videoFile.setFileLength(message.timelen);
        videoFile.setFileSize(message.length);
        videoFile.setFilePath(message.path);
        videoFile.setOwnerId(coreManager.getSelf().getUserId());
        VideoFileDao.getInstance().addVideoFile(videoFile);
        String path = message.path;
        if (TextUtils.isEmpty(path)) {
            ToastUtil.showToast(this, R.string.record_failed);
            return;
        }
        File file = new File(path);
        if (!file.exists()) {
            ToastUtil.showToast(this, R.string.record_failed);
            return;
        }
        ShowVideoView(path);
    }

    private void ShowVideoView(String path){
        mVideoFilePath = path;
        if (VideoUtil.getLocalVideoDuration(mVideoFilePath)/1000>60){
            ToastUtil.showToast(mContext,"目前只支持上传1分钟以内的短视频");
            return;
        }
        ThumbnailHelper.displayVideoThumb(mContext, mVideoFilePath, iv_video.thumbImageView);
        mThumbBmp = ThumbnailHelper.makeThumb(mVideoFilePath);
        iv_video.setUp(mVideoFilePath, JVCideoPlayerStandardSecond.SCREEN_LAYOUT_NORMAL, "");
        type = 4;
        btn_title_right.setTextColor(getResources().getColor(R.color.blue));
        btn_title_right.setEnabled(true);
        mGridView.setVisibility(View.GONE);
        tv_video_time.setText(VideoUtil.getVideoDurationStr(VideoUtil.getLocalVideoDuration(path)));
        rt_video.setVisibility(VISIBLE);
        if (isVoiceShow()) {
            changeChatVoiceView(false);
        }
    }
    private class GridViewAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            if (mPhotoList.size() >= 9) {
                return 9;
            }
            return mPhotoList.size() + 1;
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public int getViewTypeCount() {
            return 2;
        }

        @Override
        public int getItemViewType(int position) {
            if (mPhotoList.size() == 0) {
                // View Type 1代表添加更多的视图
                return 1;
            } else if (mPhotoList.size() < 9) {
                if (position < mPhotoList.size()) {
                    // View Type 0代表普通的ImageView视图
                    return 0;
                } else {
                    return 1;
                }
            } else {
                return 0;
            }
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            View view = LayoutInflater.from(PublishDynamicActivity.this)
                    .inflate(R.layout.layout_circle_add_more_item_temp, parent, false);
            SquareCenterImageView iv = view.findViewById(R.id.iv);
            ImageView image_delete = view.findViewById(R.id.image_delete);
            if (mPhotoList.size() > 0) {
                type = 2;
                btn_title_right.setTextColor(getResources().getColor(R.color.blue));
                btn_title_right.setEnabled(true);
                if (isVoiceShow()) {
                    changeChatVoiceView(false);
                }
            } else {
                type = 1;
                if (TextUtils.isEmpty(edit_text.getText().toString())) {
                    btn_title_right.setTextColor(getResources().getColor(R.color.color_8C8C8C));
                    btn_title_right.setEnabled(false);
                }
            }
            if (getItemViewType(position) == 0) { // 普通的视图
                Glide.with(PublishDynamicActivity.this)
                        .load(mPhotoList.get(position))
                        .override(150, 150)
                        .error(R.drawable.pic_error)
                        .into(iv);
                image_delete.setVisibility(View.VISIBLE);
                image_delete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mPhotoList.remove(position);
                        notifyDataSetInvalidated();
                    }
                });
            } else {
                image_delete.setVisibility(View.GONE);
                iv.setImageResource(R.mipmap.img_addimg);
            }
            return view;
        }
    }

    private class UploadTask extends AsyncTask<Void, Integer, Integer> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            DialogHelper.showDefaulteMessageProgressDialog(PublishDynamicActivity.this);
        }

        /**
         * 上传的结果： <br/>
         * return 1 Token过期，请重新登录 <br/>
         * return 2 语音为空，请重新录制 <br/>
         * return 3 上传出错<br/>
         * return 4 上传成功<br/>
         */
        @Override
        protected Integer doInBackground(Void... params) {
            if (!LoginHelper.isTokenValidation()) {
                return 1;
            }

            Map<String, String> mapParams = new HashMap<String, String>();
            mapParams.put("access_token", coreManager.getSelfStatus().accessToken);
            mapParams.put("userId", coreManager.getSelf().getUserId() + "");
            mapParams.put("validTime", "-1");// 文件有效期
            String result = null;
            if (type == 2) {//图文
                result = new UploadService().uploadFile(coreManager.getConfig().UPLOAD_URL, mapParams, mPhotoList);
                if (TextUtils.isEmpty(result)) {
                    return 2;
                }
            } else if (type == 3) {//语音
                if (TextUtils.isEmpty(mVoiceFinalPath)) {
                    return 2;
                }
                List<String> dataList = new ArrayList<String>();
                dataList.add(mVoiceFinalPath);
                result = new UploadService().uploadFile(coreManager.getConfig().UPLOAD_URL, mapParams, dataList);
                if (TextUtils.isEmpty(result)) {
                    return 3;
                }
            } else if (type == 4) {//视频
                if (TextUtils.isEmpty(mVideoFilePath)) {
                    return 2;
                }
                // 保存视频缩略图至sd卡
                String imageSavePsth = CameraUtil.getOutputMediaFileUri(PublishDynamicActivity.this, CameraUtil.MEDIA_TYPE_IMAGE).getPath();
                if (!BitmapUtil.saveBitmapToSDCard(mThumbBmp, imageSavePsth)) {// 保存缩略图失败
                    return 3;
                }
                List<String> dataList = new ArrayList<String>();
                dataList.add(mVideoFilePath);
                if (!TextUtils.isEmpty(imageSavePsth)) {
                    dataList.add(imageSavePsth);
                }

                result = new UploadService().uploadFile(coreManager.getConfig().UPLOAD_URL, mapParams, dataList);
                if (TextUtils.isEmpty(result)) {
                    return 3;
                }
            }
            UploadFileResult recordResult = JSON.parseObject(result, UploadFileResult.class);
            boolean success = Result.defaultParser(PublishDynamicActivity.this, recordResult, true);
            if (success) {
                if (recordResult.getSuccess() != recordResult.getTotal()) {// 上传丢失了某些文件
                    return 3;
                }
                if (recordResult.getData() != null) {
                    UploadFileResult.Data data = recordResult.getData();
                    if (type == 2) {
                        if (data.getImages() != null && data.getImages().size() > 0) {
                            mImageData = JSON.toJSONString(data.getImages(), UploadFileResult.sImagesFilter);
                            return 4;
                        }
                    } else if (type == 3) {
                        if (data.getAudios() != null && data.getAudios().size() > 0) {
                            while (data.getAudios().size() > 1) {// 因为正确情况下只有一个语音，所以要保证只有一个语音
                                data.getAudios().remove(data.getAudios().size() - 1);
                            }
                            data.getAudios().get(0).setSize(new File(mVoiceFinalPath).length());
                            data.getAudios().get(0).setLength(RecordTime);
                            mRecordData = JSON.toJSONString(data.getAudios(), UploadFileResult.sAudioVideosFilter);
                            return 4;
                        }
                    } else if (type == 4) {
                        if (data.getImages() != null && data.getImages().size() > 0) {
                            mImageData = JSON.toJSONString(data.getImages(), UploadFileResult.sImagesFilter);
                        }
                        if (data.getVideos() != null && data.getVideos().size() > 0) {
                            while (data.getVideos().size() > 1) {// 因为正确情况下只有一个视频，所以要保证只有一个视频
                                data.getVideos().remove(data.getVideos().size() - 1);
                            }
                            data.getVideos().get(0).setSize(new File(mVideoFilePath).length());
                            data.getVideos().get(0).setLength(VideoUtil.getLocalVideoDuration(mVideoFilePath));
                            // 记录本机上传，用于快速读取，
                            UploadCacheUtils.save(PublishDynamicActivity.this, data.getVideos().get(0).getOriginalUrl(), mVideoFilePath);
                            mVideoData = JSON.toJSONString(data.getVideos(), UploadFileResult.sAudioVideosFilter);
                            return 4;
                        }
                    }
                    return 3;
                } else {
                    // 没有文件数据源，失败
                    return 3;
                }
            } else {
                return 3;
            }
        }

        @Override
        protected void onPostExecute(Integer result) {
            super.onPostExecute(result);
            if (result == 1) {
                DialogHelper.dismissProgressDialog();
                startActivity(new Intent(PublishDynamicActivity.this, SMSLoginActivity.class));
            } else if (result == 2) {
                DialogHelper.dismissProgressDialog();
                ToastUtil.showToast(PublishDynamicActivity.this, InternationalizationHelper.getString("JXAlert_NotHaveFile"));
            } else if (result == 3) {
                DialogHelper.dismissProgressDialog();
                ToastUtil.showToast(PublishDynamicActivity.this, R.string.upload_failed);
            } else {
                sendDynamic();
            }
        }
    }


    // 多张图片压缩 相册
    private void album(List<String> stringArrayListExtra, boolean isOriginal) {
        if (isOriginal) {// 原图发送，不压缩
            Log.e("zq", "原图上传，不压缩，选择原文件路径");
            for (int i = 0; i < stringArrayListExtra.size(); i++) {
                mPhotoList.add(stringArrayListExtra.get(i));
                mAdapter.notifyDataSetInvalidated();
            }
            return;
        }

        List<File> fileList = new ArrayList<>();
        for (int i = 0; i < stringArrayListExtra.size(); i++) {
            // Luban只处理特定后缀的图片，不满足的不处理也不走回调，
            // 只能挑出来不压缩，
            List<String> lubanSupportFormatList = Arrays.asList("jpg", "jpeg", "png", "webp", "gif");
            boolean support = false;
            for (int j = 0; j < lubanSupportFormatList.size(); j++) {
                if (stringArrayListExtra.get(i).endsWith(lubanSupportFormatList.get(j))) {
                    support = true;
                    break;
                }
            }
            if (!support) {
                fileList.add(new File(stringArrayListExtra.get(i)));
                stringArrayListExtra.remove(i);
            }
        }

        if (fileList.size() > 0) {
            for (File file : fileList) {// 不压缩的部分，直接发送
                mPhotoList.add(file.getPath());
                mAdapter.notifyDataSetInvalidated();
            }
        }

        Luban.with(this)
                .load(stringArrayListExtra)
                .ignoreBy(100)// 原图小于100kb 不压缩
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onSuccess(File file) {
                        mPhotoList.add(file.getPath());
                        mAdapter.notifyDataSetInvalidated();
                    }

                    @Override
                    public void onError(Throwable e) {

                    }
                }).launch();// 启动压缩
    }
}
